const db = wx.cloud.database()
const util = require('../../../utils/utils.js')
let openid = ''
Page({
  data: {
    hasEmptyGrid: false, //用于判断留白区域
  },

  onLoad: async function(options) {
    // 获取时间
    const date = new Date();
    const curYear = date.getFullYear();
    const curMonth = date.getMonth() + 1;
    const weeksCh = ['日', '一', '二', '三', '四', '五', '六'];
    // 计算1号是星期几
    this.calculateEmptyGrids(curYear, curMonth);
    // 每月有多少天
    let days = this.calculateDays(curYear, curMonth);
    this.setData({
      curYear,
      curMonth,
      weeksCh
    });
    this.initRecords(days, curYear, curMonth)
  },

  // 页面渲染
  async initRecords(days, year, month) {
    let detail = await this.getSignRcords()
    let signTotal = detail.length
    let signTime = signTotal && detail[0].sign_time
    let continueDays = signTotal && detail[0].continue_sign_days
    // 把数据转换为一个对象
    let records = this.convertToObject(detail)
    this.signRecord(records, days, year, month)
    // 判断当天是否已签到
    let isSameDay = util.isSameDay(signTime, Date.now())
    this.setData({
      signTotal,
      signed: isSameDay,
      continueDays
    })
  },

  // 查询数据库的历史签到信息
  async getSignRcords() {
    wx.cloud.callFunction({
      name: "login"
    }).then(res => {
      openid = res.result.userInfo.openId
      console.log(openid)
    }).catch(err => {
      console.log(err)
    })

    let {
      data
    } = await db.collection('sign').where({
      _openid: openid
    }).orderBy("sign_time", "desc").get()
    // 数据格式化：****/**/**
    for (let item in data) {
      data[item].sign_time = util.formatDate(data[item].sign_time, "/")
    }
    wx.setStorageSync('signDetail', data)
    return data
  },

  getThisMonthDays(year, month) {
    return new Date(year, month, 0).getDate();
  },

  getFirstDayOfWeek(year, month) {
    return new Date(Date.UTC(year, month - 1, 1)).getDay();
  },

  // 计算留白大小
  calculateEmptyGrids(year, month) {
    // 获取月份的第一天是星期几
    const firstDayOfWeek = this.getFirstDayOfWeek(year, month);
    let empytGrids = [];
    if (firstDayOfWeek > 0) {
      for (let i = 0; i < firstDayOfWeek; i++) {
        empytGrids.push(i);
      }
      this.setData({
        hasEmptyGrid: true,
        empytGrids
      });
    } else {
      this.setData({
        hasEmptyGrid: false,
        empytGrids: []
      });
    }
  },

  convertToObject(array, key) {
    let obj = {}
    array.forEach((item) => {
      obj[item.sign_time] = item
    })
    return obj
  },

  // 计算天数
  calculateDays(year, month) {
    let days = [];
    const thisMonthDays = this.getThisMonthDays(year, month);
    for (let i = 1; i <= thisMonthDays; i++) {
      days.push({
        day: i,
        choosed: false
      });
    }
    return days
  },

  // 切换月份
  handleCalendar(e) {
    console.log(e)
    const handle = e.currentTarget.dataset.handle;
    const curYear = this.data.curYear;
    const curMonth = this.data.curMonth;
    if (handle === 'prev') {
      let newMonth = curMonth - 1;
      let newYear = curYear;
      if (newMonth < 1) {
        newYear = curYear - 1;
        newMonth = 12;
      }
      let days = this.calculateDays(newYear, newMonth);
      this.calculateEmptyGrids(newYear, newMonth);
      let detail = wx.getStorageSync('signDetail')
      let records = this.convertToObject(detail)
      this.signRecord(records, days, newYear, newMonth)
      this.setData({
        curYear: newYear,
        curMonth: newMonth
      });
    } else {
      let newMonth = curMonth + 1;
      let newYear = curYear;
      if (newMonth > 12) {
        newYear = curYear + 1;
        newMonth = 1;
      }
      let days = this.calculateDays(newYear, newMonth);
      this.calculateEmptyGrids(newYear, newMonth);
      let detail = wx.getStorageSync('signDetail')
      let records = this.convertToObject(detail)
      this.signRecord(records, days, newYear, newMonth)
      this.setData({
        curYear: newYear,
        curMonth: newMonth
      });
    }
  },

  signRecord(records, days, year, month) {
    month = util.formatNumber(month)
    if (Object.keys(records).length) {
      days.forEach((item, index, array) => {
        let day = util.formatNumber(item.day)
        array[index].choosed = Boolean(records[`${year}/${month}/${day}`])
      })
    }
    this.setData({
      days
    })
  },

  // 点击签到
  sign: async function() {
    this.setData({
      sign: true
    })
    await wx.cloud.callFunction({
      name: "sign"
    }).then(res => {
      let {
        days,
        curMonth,
        curYear
      } = this.data
      this.initRecords(days, curYear, curMonth).then(res => {
          // console.log(this.data.continueDays)
          wx.cloud.callFunction({
            name: "integral",
            data: {
              openid,
              sense: 1, //1:加积分，0：减积分
              continueDays: this.data.continueDays
            }
          }).then(res => {
            // console.log(res)
            wx.cloud.callFunction({
              name: 'seek',
              data: {
                openid,
                $url: 'updateuserinfo',
              }
            }).then((res) => {})
          })
        })
        .catch((error) => {
          console.log(error)
          this.setData({
            sign: false
          })
        })
    })

    this.setData({
      signed: true
    })
    wx.showModal({
      title: "签到提醒",
      content: "签到成功，天天坚持哦",
      showCancel: false
    })
  },

  onShareAppMessage: function() {}
})